using System;
using System.Collections.Generic;
using Gameplay.RTS.ScriptConfig;
using LogSystem;
using RuntimeInspectorNamespace;
using UnityEngine;
using XLua;
using Yoozoo.Managers.ResourceManagerV2.Runtime;
using Yoozoo.Mars.Got;
using Yoozoo.Mars.Got.SpriteAnim;

namespace Yoozoo.Gameplay.RTS
{
    public class RTSSpriteManager
    {
		public static RTSSpriteManager Inst;
        private SpriteParticleSystemManager systemManager;
        private Dictionary<string, int> soldiersDic = new Dictionary<string, int>();
		private Dictionary<string,Sprite[]> spritePool = new Dictionary<string, Sprite[]>();
        /// <summary>
        /// 阵营色
        /// </summary>
        private Dictionary<int, MaterialPropertyBlock> propertyBlocks = new Dictionary<int, MaterialPropertyBlock>();
        private MaterialPropertyBlock commanderBlock;
        //涉及到的资源名
        private List<string> resourceModleName;
        /// <summary>
        /// 后缀，用于不同颜色的行军士兵，需要不同prefab
        /// </summary>
        public static string postfix;

        //private List<Color[]> colorList = new List<Color[]>
        //{
        //    new Color[]{Color.green,Color.green,Color.green },
        //    new Color[]{Color.blue, Color.blue, Color.blue },
        //    new Color[]{Color.red, Color.red, Color.red },
        //};
        public Material shadowMat;
        private readonly string shaderPath = "Mobile/World/Sprites/Color";
        private readonly string materalName = "Assets/ResourcesAssets/FrameAnimation/world_march_run.mat";
        private readonly string frameAnimationRoot = "FrameAnimation/";

        private readonly string _MaskColor1 = "_MaskColor1";
        private readonly string _MaskColor2 = "_MaskColor2";
        private readonly string _MaskColor3 = "_MaskColor3";
        private readonly string ColorMaskTex = "_CampMaskTex";
        private readonly string ShadowColor = "_ColorTwo";
        private readonly string _Alpha = "_Alpha";


        private Dictionary<string, Texture> maskDic = new Dictionary<string, Texture>();
        private int resCount = 0;
        private int frameDataCount = 0;
        
        private Action onLoadOver;
        private RTSResourceManager _resourceManager;
        private List<string> _preloadSoldierAtlas;
        public void Init()
        {
            Inst = this;
            systemManager = ArmyManager.SpriteParticleSystemManager;
        }
        
        public void LoadSoldiers(RTSResourceManager resourceManager, Action onLoadOver)
        {
            this.onLoadOver = onLoadOver;
            _resourceManager = resourceManager;
            if (resourceModleName == null)
            {
                onLoadOver?.Invoke();
            }
            else
            {
                loadSoliderRes();
            }
//            InitSoliders();
        }
       
        public void CalMonsterNeedLoadSoldierAtlas(LuaTable soldierList)
        {
            for (int i = 1; i <= soldierList.Length; i++)
            {
                if (resourceModleName == null)
                {
                    resourceModleName = new List<string>();
                }
                var atlasName = soldierList.Get<int, string>(i);
                
                resourceModleName.Add(atlasName);
            }
        }
        private void InitSoliders()
        {
            InitResource();
        }

        /// <summary>
        /// 加载资源
        /// </summary>
        private void InitResource()
        {
            postfix = "1";
            resourceModleName = new List<string>();
            var enumerator = _resourceManager.GetSoldierModelInfoDic().GetEnumerator();
            while (enumerator.MoveNext())
            {
                AddSoldiers(enumerator.Current.Value.id);
            }
            enumerator.Dispose();
            //AddSoldiers(BattleUtils.AmbulanceSoldierName);
            AddSoldiers(BattleUtils.ScoutSoldierName);
//            AddSoldiers(BattleUtils.ScureSoldierName);
            loadSoliderRes();
        }

        private void loadSoliderRes()
        {
            resCount = resourceModleName.Count;
            frameDataCount = resourceModleName.Count;
            var loader = ResLoader.Alloc();
            foreach (var altasName in resourceModleName)
            {
                systemManager.LoadSprite(altasName, () =>
                {
                    frameDataCount--;
                    if (frameDataCount == 0)
                    {
                        foreach (var altasName2 in resourceModleName)
                        {
                            //for (int i = 0; i < 2; i++)
                            {
                                int i = 0;
                                var offset = _resourceManager.GetModelYOffsetByName(altasName2);
                                systemManager.CreateSpriteCreator(altasName2, altasName2 + i, materalName,OnLoadEnd,0, offset);
                            }
                        }
                    }
                    CheckLoadEnd();
                });
            }
            loader.Load();
        }
        private Dictionary<string,List<Action<AnimSpriteCreator>>> loadOverCallBack = new Dictionary<string, List<Action<AnimSpriteCreator>>>();
        public void LoadSingleSoldierRes(string altasName, Action<AnimSpriteCreator> onloadOver)
        {
            if (ArmyManager.IsDebugSpriteLoading)
            {
                MarchHelper.Log("尝试加载单张图集"+altasName);
            }
            if (systemManager.HasAdd2LoadSprite(altasName))
            {
                if (!loadOverCallBack.TryGetValue(altasName,out var list))
                {
                    list = new List<Action<AnimSpriteCreator>>();
                    loadOverCallBack.Add(altasName,list);
                }
                list.Add(onloadOver);
                if (ArmyManager.IsDebugSpriteLoading)
                {
                    var creator = systemManager.GetSpriteCreatorByOriginNameAndTeam(altasName, 0);
                    var createName = "Null";
                    if (creator != null)
                    {
                        createName = "CreatorName";
                    }
                    MarchHelper.Log("已经存在单张图集"+altasName + " Creator = " + createName);
                }
            }
            else
            {
                systemManager.LoadSprite(altasName, () =>
                {
                    int i = 0;
                    var offset = _resourceManager.GetModelYOffsetByName(altasName);
                    if (ArmyManager.IsDebugSpriteLoading)
                    {
                        MarchHelper.Log("单张图集加载成功"+altasName);
                    }
                    systemManager.CreateSpriteCreator(altasName, altasName + i, materalName, (creator) =>
                    {
                        if (loadOverCallBack.TryGetValue(altasName, out var list))
                        {
                            foreach (var calback in list)
                            {
                                calback?.Invoke(creator);
                            }

                            loadOverCallBack.Remove(altasName);
                        }

                        if (ArmyManager.IsDebugSpriteLoading)
                        {
                            MarchHelper.Log("单张图集的Creator创建成功"+altasName);
                        }
                        onloadOver.Invoke(creator);
                    }, 0, offset);
                });
            }
        }


        private void OnLoadEnd(AnimSpriteCreator creator)
        {
            string num = creator.CreatorName.Substring(creator.CreatorName.Length - 1);
            string name = creator.CreatorName.Substring(0,creator.CreatorName.Length - 1);
            int team = 0;
            int.TryParse(num, out team);

            MaterialPropertyBlock propertyBlock = new MaterialPropertyBlock();
            if (team == 0)
            {
                propertyBlock.SetColor(ShadowColor, MarchHelper.ShadowColors[0]);
            }
            else
            {
                propertyBlock.SetColor(ShadowColor, MarchHelper.ShadowColors[1]);
            }
            propertyBlock.SetInt("_CampType", 1);
            systemManager.SetRendererPropertyBlock(creator, propertyBlock);

            //Color[][] colors = _resourceManager.GetColorByName(name);

            //var maskColors = colors[team];
            //propertyBlock.SetVector(_MaskColor1, maskColors[0]);
            //propertyBlock.SetVector(_MaskColor2, maskColors[1]);
            //propertyBlock.SetVector(_MaskColor3, maskColors[2]);

            //if (maskDic.ContainsKey(name))
            //{
            //    creator.ParticlesMaterial.SetTexture(ColorMaskTex, maskDic[name]);
            //}
            //systemManager.SetRendererPropertyBlock(creator, propertyBlock);
            resCount--;
        }

        private void CheckLoadEnd()
        {
            ArmyManager.loadingCallBack?.Invoke(resourceModleName.Count - frameDataCount, resourceModleName.Count, "soldier");

            if (resCount <= 0 && frameDataCount <= 0)
            {
                Debug.Log("load soldier complete");
                onLoadOver?.Invoke();
            }
        }
        
        private void AddSoldiers(string modleName)
        {
            if (string.IsNullOrEmpty(modleName))
            {
                return;
            }

            if (!resourceModleName.Contains(modleName))
            {
                resourceModleName.Add(modleName);
            }
        }


        public static readonly Color MODEL_COLOR = new Color(150f / 255f, 150f / 255f, 150f / 255f, 1f);
        
        public void Dispose()
        {
            soldiersDic.Clear();
            soldiersDic = null;
			spritePool.Clear();
            spritePool = null;
            _resourceManager = null;
        }

#if UNITY_EDITOR
        public void ResetColorMaskBlock()
        {
            var visitorList = ArmyManager.SpriteParticleSystemManager.GetAllVisitor();
            for (int i = 0; i < visitorList.Count; i++)
            {
                for (int j = 0; j < visitorList[i].Count; j++)
                {
                    var creator = visitorList[i][j];
                    string num = creator.CreatorName.Substring(creator.CreatorName.Length - 1);
                    string name = creator.CreatorName.Substring(0, creator.CreatorName.Length - 1);
                    int team = 0;
                    int.TryParse(num, out team);

                    Color[][] colors = _resourceManager.GetColorByName(name);

                    var maskColors = colors[team];
                    MaterialPropertyBlock propertyBlock = new MaterialPropertyBlock();
                    propertyBlock.SetVector(_MaskColor1, maskColors[0]);
                    propertyBlock.SetVector(_MaskColor2, maskColors[1]);
                    propertyBlock.SetVector(_MaskColor3, maskColors[2]);

                    systemManager.SetRendererPropertyBlock(creator, propertyBlock);
                }
            }

        }
#endif
       
    }
}
